const express = require("express");
let users = require("./user.json");
const fs = require('fs');
const { log } = require("console");
let app = express()
app.use(express.json());

// 登录
app.post("/login", (req, res) => {
  // console.log(req.url);
  let { username, password } = req.body
  // console.log(username, password);
  // console.log(users);  // [admin, admin]
  let user = users.filter(item => item.username === username && item.password === password)
  console.log(user.length);
  if (user.length) {
    res.json(
      {
        username: user.username,
        password: user.password,
        state: '111'
      }
    )
  } else {
    res.json(
      {
        username: user.username,
        password: user.password,
        state: '000'
      }
    )
  }
},

  // 注册
  app.post('/register', (req, res) => {
    try {
      console.log(req.url);
      let users = JSON.parse(fs.readFileSync("./user.json"))
      users.push(req.body)
      fs.writeFileSync("./user.json", JSON.stringify(users))
      res.json({
        info: "成功",
        state: '111'
      })
    } catch (err) {
      res.json({
        info: "成功",
        state: '000'
      })
    }

  }),

  // 虚假功能方法
  app.post('/userData', (req, res) => {
    try {
      console.log(req.url);
      let users = JSON.parse(fs.readFileSync("./user.json"))
      let userData = users[users.length - 1]
      console.log(userData);
      res.json({
        info: '成功',
        username: userData.username
      })
    } catch (err) {
      res.json({
        info: "失败",
        username: ""
      })
    }

  }),

  // 注销用户
  app.get('/logout', (req, res) => {
    // console.log(111);
    try {
      console.log(req.url);
      let users = JSON.parse(fs.readFileSync("./user.json"))
      console.log(typeof users);
      users.splice(users.length - 1, 1)
      fs.writeFileSync("./user.json", JSON.stringify(users))
      res.json({
        info: "成功",
        state: "111"
      })
    } catch (err) {
      res.json({
        info: "失败",
        state: "000"
      })
    }



  })

)
app.listen(8989) 